import AuthUtil from '@src/util/auth'
import FormMixin from '@src/component/form/mixin/form'
import { saveFileToLink } from 'web-downloadfile';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
import { linkmanSelectConversion } from '@src/util/conversionFunctionUtil.ts'
import * as TaskApi from '@src/api/TaskApi.ts';
import * as IMApi from '@src/api/ImApi.js';
import { getCustomerList } from '@src/api/CustomerApi'
import i18n from '@src/locales'
import { TEL_REG,PHONE_REG} from '@src/util/validator.js'
export default {
  name: 'chat-mixin',
  inject: ['initData'],
  data() {
    return {
      saveDialogVisible: false,
      saveForm: {
        name: '', // 新建联系人方式的联系人
        phone: '',
        type:0,
        linkman:'', // 更新原有联系人方式的联系人
        email:'', // 邮箱
      },
      saveFormRules: {
        name: [{ required: true, message: i18n.t('im.chatMixin.tips1'), trigger: ['blur', 'change']}],
        phone: [
          { required: true, message: i18n.t('im.chatMixin.tips2'), trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (TEL_REG.test(value) || PHONE_REG.test(value)) {
                callback();
              } else {
                callback(new Error(i18n.t('im.chatMixin.tips3')));
              }
            },
          },
        ],
        email: [
          { required: true, message: i18n.t('im.chatMixin.tips4'), trigger: 'blur' },
        ],
        customer:[
          { 
            required:true,
            validator:(rule, value, callback)=>{
              if(this.customer[0].value){
                callback();
              }else{
                callback(new Error(i18n.t('im.chatMixin.tips5')));
              }
            }, 
            trigger: 'blur'
          },
        ],
        type: [
          { required: true, message: i18n.t('im.chatMixin.tips6'), trigger: ['blur', 'change']},
        ],
        linkman: [{ required: true, message: i18n.t('im.chatMixin.tips7'), trigger: ['blur', 'change']}],
      },
      customer: [
        {
          value: '',
          label: ''
        }
      ],
      customerField: {
        isSystem: 1,
        fieldName: 'customer',
        displayName: i18n.t('common.base.customer'),
        formType: 'customer',
        defaultValue: null,
        isNull: 0,
        isSearch: 0,
        placeHolder: ''
      },
      isAssociated: false,
      AssociatedForm: {
        conversationId: '',
        source: '',
        linkmanId: '',
        phoneNumber: '',
        wechatUserId: ''
      },
      AssociatCustomer: [
        {
          value: '',
          label: ''
        }
      ],
      AssociatedFormRules: {
        linkmanId: [{ required: true, message: i18n.t('im.chatMixin.tips7'), trigger: ['blur', 'change'] }],
        phoneNumber: [
          { required: true, message: i18n.t('im.chatMixin.tips2'), trigger: 'blur' },
          { pattern: /^[1]([3-9])[0-9]{9}$/, message: i18n.t('im.chatMixin.tips3') }
        ]
      },
      isInformation: false
    }
  },
  components: {
    'customer-select': {
      name: 'customer-select',
      mixins: [FormMixin],
      props: {
        value: {
          type: Array,
          default: () => []
        },
        remoteMethod: Function,
        updateCustomer: Function,
        placeholder: String
      },
      methods: {
        input(value) {
          this.$emit('input', value)
        }
      },
      render(h) {
        return (
          <base-select
            value={this.value}
            placeholder={this.placeholder}
            remoteMethod={this.remoteMethod}
            onInput={this.updateCustomer}
          />
        )
      }
    }
  },
  filters: {
    formatStatus(val) {
      let status = i18n.t('common.base.notRead')
      switch (val) {
      case 0:
        status = i18n.t('common.base.notSend')
        break;
      case 1:
        status = i18n.t('common.base.haveSend')
        break;
      case 2:
        status = i18n.t('common.base.notRead')
        break;
      case 3:
        status = i18n.t('common.base.haveRead')
        break;
      default:
        break;
      }
      return status;
    },
  },
  computed: {
    auths() {
      return this.initData?.auths || {}
    },
    allowCreateTask() {
      return AuthUtil.hasAuth(this.auths, 'TASK_ADD')
    },
    allowCreateEvent() {
      return AuthUtil.hasAuth(this.auths, 'CASE_ADD')
    },
    allowCreateCustomer() {
      return AuthUtil.hasAuth(this.auths, 'CUSTOMER_CREATE')
    },
    allowCreateLinkman() {
      return AuthUtil.hasAuth(this.auths, 'LINKMAN_ADD')
    },
    isWeChat() {
      return this.source == 'weChat'
    },
  },
  methods: {
    createCustomerTab(customerId) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `customer_view_${customerId}`,
      //   title: '客户信息',
      //   close: true,
      //   url: `/customer/view/${customerId}?noHistory=1`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
        fromId
      })
    },
    createTask(customerId, conversationNo, defaultTypeId = '', refresh = true,linkmanId) {
      // const params = {
      //   id: 'createTask',
      //   title: '新建工单',
      //   close: true,
      //   url: `/task/createFromCustomer/${customerId}?conversationNo=${conversationNo}&defaultTypeId=${defaultTypeId}`,
      // }
      const param = {
        type: PageRoutesTypeEnum.PageCreateTaskFromCustomer,
        key: customerId,
        params: `conversationNo=${conversationNo}&defaultTypeId=${defaultTypeId}&linkmanId=${linkmanId}`,
      }
      if(refresh){
        let fromId = window.frameElement.getAttribute('id')
        param.fromId = fromId
      }
      openAccurateTab(param)
      // this.$platform.openTab(params)
    },
    Improve(conversationId, linkmanPhone, customerId) {
      // 微信客服 创建客户时，将微信昵称带入联系人名称，保存客户后同时保存联系人信息；同时在联系人表中记录该联系人的微信昵称、性别、微信id等信息；
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'customer_edit1',
      //   title: '完善客户信息',
      //   url: `/customer/supplementCustomerInfo?lmPhone=${linkmanPhone}&conversationId=${conversationId}&source=${this.source}&wechatUserId=${this.wechatUserId}&customerId=${customerId}`,
      //   reload: true,
      //   close: true,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSupplementCustomerInfo,
        params: `lmPhone=${linkmanPhone}&conversationId=${conversationId}&source=${this.source}&wechatUserId=${this.wechatUserId}&customerId=${customerId}`,
        reload: true,
        fromId
      })
    },
    createEvent(customerId, conversationNo, defaultTypeId = '', refresh = true, linkmanId) {
      // 将客户信息带入
      // const { customerId, conversationNo } = this.userDetail
      // const params = {
      //   id: 'createEvent',
      //   title: '新建事件',
      //   close: true,
      //   url: `/event/createFromCustomer/${customerId}?conversationNo=${conversationNo}&defaultTypeId=${defaultTypeId}`,
      // }
      const param = {
        type: PageRoutesTypeEnum.PageCreateEventFromCustomer,
        key: customerId,
        params: `conversationNo=${conversationNo}&defaultTypeId=${defaultTypeId}&linkmanId=${linkmanId}`,
      }
      if(refresh){
        let fromId = window.frameElement.getAttribute('id')
        param.fromId = fromId
      }
      openAccurateTab(param)
      // this.$platform.openTab(params)
    },
    createPass(obj) {
      let fromId = window.frameElement.getAttribute('id');
      const params = {
        id: `frame_tab_create_view_${obj.passMenuId}`,
        title: this.$t('common.pageTitle.otherPageTitle.createNewForm'),
        close: true,
        url: obj.url,
        fromId
      }
      this.$platform.openTab(params)
    },
    createCustomer(conversationId, linkmanPhone, lmEmail) {
      // 微信客服 创建客户时，将微信昵称带入联系人名称，保存客户后同时保存联系人信息；同时在联系人表中记录该联系人的微信昵称、性别、微信id等信息；
      // let { conversationId } = this.hxIdObj
      // const { linkmanPhone } = this.userDetail
      conversationId = conversationId || ''
      linkmanPhone = linkmanPhone || ''
      lmEmail = lmEmail || ''
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'customer_create',
      //   title: '新建客户',
      //   url: this.isWeChat ? '/customer/create' : `/customer/create?lmPhone=${linkmanPhone}&conversationId=${conversationId}`,
      //   reload: true,
      //   close: true,
      //   fromId
      // });
      const param = {
        type: PageRoutesTypeEnum.PageCreateCustomer,
        reload: true,
        params: `lmPhone=${linkmanPhone}&conversationId=${conversationId}&lmEmail=${lmEmail}`,
        fromId
      }
      openAccurateTab(param)
    },
    saveLinkman(linkmanPhone, linkmanEmail) {
      this.saveDialogVisible = true
      if (!this.isWeChat) {
        this.saveForm.phone = linkmanPhone
        this.saveForm.email = linkmanEmail
      }
    },
    saveUser(conversationId) {
      return new Promise((resolve, reject)=>{
        this.$refs.saveFormRef.validate(async valid => {
          if (!valid) return reject(this.$t('im.chatMixin.tips8'))
          const params = {}
          const {email, linkman, name, phone, type } = this.saveForm
          params.conversationId = conversationId
          params.customerId = this.customer[0].value
          params.customerName = this.customer[0].label
          params.phoneNumber = phone
          params.email = email
          if(type == 0){
            params.linkmanName = name
          }else{
            params.linkmanName = linkman[0].name
            params.linkmanId = linkman[0].id
          }
          if (this.isWeChat && !params.phoneNumber) {
            this.loading = false
            return this.$platform.alert(this.$t('im.chatMixin.tips9'))
          }
          let confirmTitle = type == 0 ? this.$t('im.chatMixin.tips10') : this.$t('im.chatMixin.tips11')
          let confirmText = type == 0 ? this.$t('im.chatMixin.tips12') : this.$t('im.chatMixin.tips13')
          const confirmRes = await this.$confirm(confirmText, confirmTitle).then(() => {
            return Promise.resolve(true)
          }).catch(() => {
            this.loading = false
            return Promise.resolve(false)
          });
          if(!confirmRes) return
          try {
            const { code, message } = await IMApi.unknownUserRelationLinkman(params)
            if (code !== 0){
              this.$platform.notification({
                title: this.$t('common.base.tip.saveFail'),
                message: message || '',
                type: 'error'
              })
              return reject(message)
            }
            this.$refs.saveFormRef.resetFields()
            this.saveDialogVisible = false
            this.isInformation = false
            this.$platform.notification({
              title: this.$t('common.base.tip.saveSuccess'),
              type: 'success'
            })
            // 页面刷新
            this.$emit('refresh')
            resolve()
          } catch (e) {
            console.error(e)
            reject(this.$t('common.base.tip.systemIsError'))
          } finally {
            this.loading = false
          }
        })
      })
    },
    saveDialogClosed() {
      this.$refs.saveFormRef.resetFields()
    },
    searchCustomer(params) {
      const pms = params || {}
      return getCustomerList(pms)
        .then(res => {
          if (!res || !res.list) return
          if (res.list) {
            res.list = res.list.map(customer =>
              Object.freeze({
                label: customer.name,
                value: customer.id
              })
            )
          }
          return res
        })
        .catch(e => console.error(e))
    },
    updateCustomer(value) {
      this.customer = value
      this.$refs.saveFormRef.validateField('customer');
    },
    readablizeBytes(value) {
      let s = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
      let e = Math.floor(Math.log(value) / Math.log(1024));
      return `${(value / Math.pow(1024, Math.floor(e))).toFixed(2)} ${s[e]}`;
    },
    preview(item) {
      // fileName, fileSize, url, id, downloadUrl, fileType
      let fileName = this.compatibleFieldByExt(item, 'filename')
      let fileSize = this.readablizeBytes(this.compatibleFieldByExt(item, 'file_length'))
      let url = this.compatibleFieldByExt(item, 'url')
      let downloadUrl = this.compatibleFieldByExt(item, 'url')
      let messageType = item.messageType
      const fileType = this.judgedFileType(fileName).split('.')[0]
      // 微信端发送的文件格式与app附件有差异，主要体现在文件url格式上
      if (fileType == 'image' || messageType == 'image' || messageType == 'newImage') {
        this.$previewElementImg(url);
      } else if (fileType == 'pdf') {
        this.$previewPDF(url);
      } else if (fileType == 'video' || messageType == 'video') {
        this.$previewVideo(url, {
          fileType:'video'
        });
      }else if (fileType === 'audio' || messageType === 'vioce') {
        this.$previewVideo(url, {
          fileType:'audio'
        });
      }
      // if(fileType == 'image' || fileType == 'video' || fileType == 'audio') {
      //   this.previewFile.fileType = fileType
      //   this.$refs.bizPreviewFileDialog.open() 
      // }
    },
    download(url, filename) {
      saveFileToLink(url, filename, this.judgedFileType(filename).split('.')[0])
    },
    showDownload(filename) {
      const fileType = this.judgedFileType(filename).split('.')[0]
      if (fileType == 'image' || fileType == 'video' || fileType == 'pdf') {
        return false
      }
      return true
    },
    judgedFileType(filename) {
      if (!filename) return 'file.png';
      const fn = filename.toLocaleLowerCase()
      if (/\.(png|bmp|gif|jpg|jpeg|tiff)$/i.test(fn)) {
        return 'image.png';
      }
      if (/\.(ppt|pptx)$/i.test(fn)) {
        return 'ppt.png';
      }
      if (/\.(mp3|amr)$/i.test(fn)) {
        return 'audio.png';
      }
      if (/\.(avi|wmv|mpeg|mp4|mov|mkv|flv|f4v|m4v|rmvb|rm|3gp)$/i.test(fn)) {
        return 'video.png';
      }
      if (/\.(zip)$/i.test(fn)) {
        return 'zip.png';
      }
      if (/\.(pdf)$/i.test(fn)) {
        return 'pdf.png';
      }
      if (/\.(xls|xlsx)$/i.test(fn)) {
        return 'xls.png';
      }
      if (/\.(doc|docx)$/i.test(fn)) {
        return 'doc.png';
      }
      if (/\.(txt)$/i.test(fn)) {
        return 'txt.png';
      }
      return 'file.png';
    },
    // 关联联系人
    saveAssociated(conversationId) {
      this.AssociatedForm.conversationId = conversationId
      this.AssociatedForm.source = this.source
      this.AssociatedForm.wechatUserId = this.wechatUserId
      this.isAssociated = true
    },
    AssociatedClosed() {
      this.$refs.Associated.resetFields()
    },
    AssociatedCustomer(value) {
      this.AssociatCustomer = value
      this.AssociatedForm.linkmanId = value[0].value || ''
    },
    AssociatedSearchCustomer(params) {
      const pms = params || {}
      return this.$http
        .post('/api/elasticsearch/outside/es/linkman/list', pms)
        .then(res => {
          if (!res || !res.result.list) return
          if (res.result.list) {
            res.list = res.result.list.map(customer =>
              Object.freeze({
                label: customer.name,
                value: customer.id
              })
            )
          }
          return res
        })
        .catch(e => console.error(e))
    },
    saveAssociate() {
      this.$refs.Associated.validate((valid) => {
        if (valid) {
          this.$http
            .post('/api/im/outside/im/user/relationLinkman', this.AssociatedForm)
            .then((res) => {
              if (res.code !== 0)
                return this.$platform.notification({
                  title: this.$t('common.base.tip.bindFail'),
                  message: res.message || '',
                  type: 'error'
                })
              this.$refs.Associated.resetFields()
              this.isAssociated = false
              this.isInformation = false
              this.$platform.notification({
                title: this.$t('common.base.tip.bindSuccess'),
                type: 'success'
              })
              // 页面刷新
              this.$emit('refresh')
            })
            .catch(e => console.error(e))
        }
      })
    },
    /**
     * 兼容环信和微信客服消息数据结构问题
     * 微信数据之前不带 ext字段
     * 
     */
    compatibleFieldByExt(item, key){
      return item.messageContent?.[key] ?? item.messageContent?.ext?.[key] ?? item.messageContent?.customExts?.[key] ?? ''
    },
    
    /**
     * 兼容环信和微信客服消息数据结构问题
     * h5的机器人消息带customExts 微信客服的不带customExts
     * 
     */
    compatibleFieldByCustomExts(item, key){
      return item.messageContent?.[key] ?? item.messageContent?.customExts?.[key] ?? item.messageContent?.ext?.[key] ?? ''
    },
    // 搜索linkman联系人
    async searchLinkman(params = {}) {
      let customerId = this.customer[0]?.value
      if(!customerId) return this.$message.error(this.$t('im.chatMixin.tips14'))
      params = {...params, customerId}
      try {
        let { result } = await TaskApi.getTaskCustomerLinkman(params);
        if (!result || !result.list) return;
        result.list = result.list.map((linkman) =>
          linkmanSelectConversion(linkman)
        );
        return result;
      } catch (error) {
        console.warn('task-edit-form: searchProduct -> error', error);
      }
    },
    // 多图预览
    chatImgPreview(currentUrl){
      try {
        let imgDoms = document.querySelectorAll('.chat-preview-img img') || []
        let urls = Array.from(imgDoms).map(item=>item.getAttribute('src'))
        this.$previewElementImg(currentUrl,urls)
      } catch(err){
        console.log(err)
        this.$previewElementImg(currentUrl)
      }
    }
  }
}